//
//  OAuthController.swift
//  sinaBlog
//
//  Created by tianxiangyang on 15/12/13.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthController: UIViewController,UIWebViewDelegate {
    
    let webView = UIWebView()
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }
    
    //App key：1219627862
    //App secret：80ba3d4e5f5abaca1c74496e4e50803f
    //https://api.weibo.com/oauth2/authorize
    //回调地址:www.baidu.com
    
    
    

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "close", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动的填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoInsertAccount")
        
        
        //加载授权回调页
        
        loadPage()

        
    }
    
    
    
    func loadPage(){
    
        /*
        //1.urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
        */
    
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        webView.loadRequest(NSURLRequest(URL: url!))
    
    }
    
    //MARK :webView的代理方法
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            //需要根据请求的url 去屏蔽不希望加载的页面
        
        
        let urlString = request.URL?.absoluteString
        
            if urlString == nil  {
                
                return false
 
            }
            
            if urlString!.hasPrefix("https://api.weibo.com/") {
                //希望加载的页面
                return true
            }
            
            if !urlString!.hasPrefix("http://www.baidu.com") {
                //一定不是请求成功后的回调  同样也不会是 我们希望加载的页面
                return false
            }
            
            //程序走到这里 一定是请求成功后的回调
            print(urlString)
            //解析字符串获取code码
            // query 获取到url中 参数部分 键值
            let query = request.URL?.query
            if let q = query {
                //字符串截取操作
                let codeStr = "code="
                let code = q.substringFromIndex(codeStr.endIndex)
                //加载用户token
                loadAccessToken(code)
            }
            return true
        }
        
        
        // MARK:加载用户token(请求标识)
        private func loadAccessToken(code: String) {
            
            UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    //为了解决model视图缓存问题,等视图dismiss完成之后再去发送通知,通知是同步执行的!!!
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: "welcome")
                    })
                    
                    
                } else {
                    print("登陆失败")
                }
            }
            
            
            
        }
        
   
    @objc private func autoInsertAccount(){
            
            let jsString = "document.getElementById('userId').value = '15890624080' ,document.getElementById('passwd').value = '1320379312' "
            webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    
    @objc private func close(){
    
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    

}
